﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TireService.Data;
using DevExpress.Web.ASPxGridView;
using DevExpress.Web.ASPxEditors;
using System.Configuration;

namespace TireService.Web.View.ResourceView
{
    public partial class ServiceCarList : System.Web.UI.Page
    {

        #region Public Properties

        public List<int> EditServiceCars
        {
            get
            {
                if (ViewState["_editservicecars"] != null)
                    return (List<int>)ViewState["_editservicecars"];
                else
                    return null;
            }
            set
            {
                ViewState["_editservicecars"] = value;
            }
        }

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            TireServiceDB db = new TireServiceDB();

            if (Page.IsPostBack != true)
            {

            }

            // Bind container data to gridview
            BindServiceCarData(db);
            try
            {
                int servicecarid = Convert.ToInt32(gvServiceCar.GetRowValues(gvServiceCar.FocusedRowIndex, "ServiceCarId"));
                BindContainerServiceCarCoverage(db, servicecarid);
            }
            catch (Exception)
            {
                // Nothing - no container selected
            }

            // Change gridview pagesize based on dropdownlist
            gvServiceCar.SettingsPager.PageSize = Convert.ToInt32(ddlPageSize.SelectedValue);

            // Dispose connection to database
            db.Dispose();
        }

        /// <summary>
        /// Function that bind service car data to gridview
        /// </summary>
        /// <param name="db">Connection to database</param>
        private void BindServiceCarData(TireServiceDB db)
        {
            gvServiceCar.DataSource = db.GetServiceCars();
            gvServiceCar.DataBind();

            // Prepare data for editmode of servicecar
            GridViewDataComboBoxColumn ddlCountry = gvServiceCar.Columns["CountryDropdown"] as GridViewDataComboBoxColumn;
            ddlCountry.PropertiesComboBox.ValueType = typeof(int);
            ddlCountry.PropertiesComboBox.DataSource = db.GetCountries();
            ddlCountry.PropertiesComboBox.TextField = "CountryName";
            ddlCountry.PropertiesComboBox.ValueField = "CountryId";
            ddlCountry.PropertiesComboBox.DropDownStyle = DropDownStyle.DropDownList;
            ddlCountry.PropertiesComboBox.IncrementalFilteringMode = IncrementalFilteringMode.StartsWith;
        }

        /// <summary>
        /// Function that bind covered containers for selected servicecar to gridview
        /// </summary>
        /// <param name="db">Connection to database</param>
        /// <param name="ServiceCarId">Id on servicecar</param>
        private void BindContainerServiceCarCoverage(TireServiceDB db, int ServiceCarId)
        {
            // Bind to gridview
            gvContainerServiceCarCoverage.DataSource = db.GetContainerServiceCarCoverageByServiceCarId(ServiceCarId);
            gvContainerServiceCarCoverage.DataBind();

            // Prepare data for editmode of container coverage
            GridViewDataComboBoxColumn ddlContainer = gvContainerServiceCarCoverage.Columns["ContainerDropdown"] as GridViewDataComboBoxColumn;
            ddlContainer.PropertiesComboBox.ValueType = typeof(int);
            //ddlContainer.PropertiesComboBox.Columns.Add("ZipCode", "Postnr");
            //ddlContainer.PropertiesComboBox.Columns.Add("ContainerNumber", "Nr");            
            ddlContainer.PropertiesComboBox.ValueField = "ContainerId";
            ddlContainer.PropertiesComboBox.TextField = "ContainerNumber";
            ddlContainer.PropertiesComboBox.DataSource = db.GetContainers();
            ddlContainer.PropertiesComboBox.DropDownStyle = DropDownStyle.DropDownList;
            ddlContainer.PropertiesComboBox.IncrementalFilteringMode = IncrementalFilteringMode.StartsWith;
        }

        #region Private Functions

        /// <summary>
        /// Function that change grouping in order gridview
        /// </summary>
        /// <param name="ViewIndex">Integer setting the grouping mode</param>
        protected void GroupOrderData(int ViewIndex)
        {
            gvServiceCar.ClearSort();
            gvServiceCar.GroupSummary.Clear();
            switch (ViewIndex)
            {
                case 0:
                    // Nothing - clear grouping

                    break;
                case 1:
                    gvServiceCar.GroupBy(gvServiceCar.Columns["City"]);

                    break;
                //case 2:
                //    gvOrder.GroupBy(gvOrder.Columns["CustomerNumber"]);

                //    break;
                //case 3:
                //    gvOrder.GroupBy(gvOrder.Columns["PhotoDate"]);
                //    gvOrder.GroupBy(gvOrder.Columns["CustomerNumber"]);

                //break;
            }
            gvServiceCar.ExpandAll();
        }

        #endregion

        #region Control Functions

        /// <summary>
        /// Button function for export of gridview
        /// </summary>
        protected void btnExport_Click(object sender, EventArgs e)
        {
            if (ddlExport.Value == "0")
            {
                gvExport.WritePdfToResponse();
            }

            if (ddlExport.Value == "1")
            {
                gvExport.WriteXlsToResponse();
            }

            if (ddlExport.Value == "2")
            {
                gvExport.WriteCsvToResponse();
            }

            if (ddlExport.Value == "3")
            {
                gvExport.WriteRtfToResponse();
            }
        }

        /// <summary>
        /// Dropdown list function that change gridview grouping when selected item is changed
        /// </summary>
        protected void ddlView_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Group data
            GroupOrderData(Convert.ToInt32(ddlView.SelectedValue));
        }

        #endregion

        #region GridView Functions

        /// <summary>
        /// Gridview function for creating servicecar
        /// </summary>
        protected void gvServiceCar_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
        {
            TireServiceDB db = new TireServiceDB();


            ServiceCar servicecar = new ServiceCar();

            servicecar.Address = Convert.ToString(e.NewValues["Address"]);
            servicecar.ZipCode = Convert.ToString(e.NewValues["ZipCode"]);
            servicecar.City = Convert.ToString(e.NewValues["City"]);
            servicecar.CountryId = Convert.ToInt32(e.NewValues["CountryId"]);
            servicecar.InActive = Convert.ToBoolean(e.NewValues["InActive"]);
            servicecar.Description = Convert.ToString(e.NewValues["Description"]);

            //// Calculate longitude and latitude for address
            //try
            //{
            //    string primaryAddress = servicecar.Address + ", " + servicecar.ZipCode + " " + servicecar.City + ", " + db.GetCountryName(servicecar.CountryId);
            //    double[] LongLatPrimary = HelperFunctions.GetLongLatCoordinates(primaryAddress, ConfigurationManager.AppSettings["MapKey"]);
            //    servicecar.Longitude = LongLatPrimary[0];
            //    servicecar.Latitude = LongLatPrimary[1];
            //}
            //catch (Exception ex)
            //{
            //    // Error calculating longitude and latitude - values will be set to null
            //}

            db.AddServiceCar(servicecar);

            // Commit changes to database
            db.SubmitChanges();

            // End edit mode
            e.Cancel = true;
            gvServiceCar.CancelEdit();

            // Refresh gridview
            BindServiceCarData(db);
            BindContainerServiceCarCoverage(db, servicecar.ServiceCarId);

            // Close db connection
            db.Dispose();
        }

        /// <summary>
        /// Gridview function for updating container
        /// </summary>
        protected void gvServiceCar_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
        {
            // Get id
            int servicecarid  = Convert.ToInt32(e.Keys["ServiceCarId"]);

            TireServiceDB db = new TireServiceDB();

            ServiceCar servicecar = new ServiceCar();

            // Instantiate business layer
            TireSetLogBLL bll = new TireSetLogBLL();

            // Fecth existing servicecar
            servicecar = db.GetServiceCar(servicecarid);

            if (servicecar != null)
            {
                servicecar.Address = Convert.ToString(e.NewValues["Address"]);
                servicecar.ZipCode = Convert.ToString(e.NewValues["ZipCode"]);
                servicecar.City = Convert.ToString(e.NewValues["City"]);
                servicecar.CountryId = Convert.ToInt32(e.NewValues["CountryId"]);
                servicecar.InActive = Convert.ToBoolean(e.NewValues["InActive"]);
                servicecar.Description = Convert.ToString(e.NewValues["Description"]);

                //// Calculate longitude and latitude for address if changed
                //if (e.OldValues["Address"] != e.NewValues["Address"] | e.OldValues["ZipCode"] != e.NewValues["ZipCode"] | e.OldValues["City"] != e.NewValues["City"] | e.OldValues["CountryId"] != e.NewValues["CountryId"])
                //{
                //    try
                //    {
                //        string primaryAddress = servicecar.Address + ", " + servicecar.ZipCode + " " + servicecar.City + ", " + db.GetCountryName(servicecar.CountryId);
                //        double[] LongLatPrimary = HelperFunctions.GetLongLatCoordinates(primaryAddress, ConfigurationManager.AppSettings["MapKey"]);
                //        servicecar.Longitude = LongLatPrimary[0];
                //        servicecar.Latitude = LongLatPrimary[1];
                //    }
                //    catch (Exception ex)
                //    {
                //        // Error calculating longitude and latitude - values will be set to null
                //    }
                //}
            }
            else
            {
                // Customer subscription does not exists
                throw new ArgumentException("Servicebil eksistere ikke");
            }

            // Commit changes to database
            db.SubmitChanges();

            // End edit mode
            e.Cancel = true;
            gvServiceCar.CancelEdit();

            // Refresh gridview
            BindServiceCarData(db);

            // Close db connection
            db.Dispose();
        }

        /// <summary>
        /// Gridview function for add service car to container coverage
        /// </summary>
        protected void gvContainerServiceCarCoverage_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
        {
            TireServiceDB db = new TireServiceDB();

            ContainerServiceCarCoverage container = new ContainerServiceCarCoverage();

            container.ServiceCarId = Convert.ToInt32(gvServiceCar.GetRowValues(gvServiceCar.FocusedRowIndex, "ServiceCarId"));
            container.ContainerId = Convert.ToInt32(e.NewValues["ContainerId"]);

            db.AddContainerServiceCarCoverage(container);

            // Commit changes to database
            db.SubmitChanges();

            // End edit mode
            e.Cancel = true;
            gvContainerServiceCarCoverage.CancelEdit();

            // Refresh gridview
            BindContainerServiceCarCoverage(db, container.ServiceCarId);

            // Close db connection
            db.Dispose();
        }

        /// <summary>
        /// Gridview function for updating service car coverage for containers
        /// </summary>
        protected void gvContainerServiceCarCoverage_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
        {
            // Get id
            int containerid = Convert.ToInt32(e.Keys["ContainerId"]);
            int servicecarid = Convert.ToInt32(gvServiceCar.GetRowValues(gvServiceCar.FocusedRowIndex, "ServiceCarId"));

            TireServiceDB db = new TireServiceDB();

            ContainerServiceCarCoverage container = new ContainerServiceCarCoverage();

            container = db.GetContainerServiceCarCoverage(servicecarid, containerid);
            container.ContainerId = Convert.ToInt32(e.NewValues["ContainerId"]);

            // Commit changes to database
            db.SubmitChanges();

            // End edit mode
            e.Cancel = true;
            gvContainerServiceCarCoverage.CancelEdit();

            // Refresh gridview
            BindContainerServiceCarCoverage(db, container.ServiceCarId);

            // Close db connection
            db.Dispose();
        }

        protected void gvContainerServiceCarCoverage_CustomCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomCallbackEventArgs e)
        {
            TireServiceDB db = new TireServiceDB();
            try
            {
                int servicecarid = Convert.ToInt32(gvServiceCar.GetRowValues(gvServiceCar.FocusedRowIndex, "ServiceCarId"));
                BindContainerServiceCarCoverage(db, servicecarid);
            }
            catch (Exception)
            {
                // Nothing - no container selected
            }

        }

        #endregion

    }
}